import 'package:flutter/material.dart';
import 'dart:math';
import '../models/word.dart';
import '../services/database_service.dart';
import '../repositories/word_repository.dart';
import '../services/ai_service.dart';

class CardMemoryScreen extends StatefulWidget {
  const CardMemoryScreen({super.key});

  @override
  State<CardMemoryScreen> createState() => _CardMemoryScreenState();
}

class _CardMemoryScreenState extends State<CardMemoryScreen> with WidgetsBindingObserver {
  bool _showMeaning = false;
  int _currentIndex = 0;
  bool _isLoading = true;
  bool _isShuffled = false;
  String _selectedCategory = '全部';
  List<String> _categories = ['全部'];
  List<Word> _words = [];
  List<Word> _filteredWords = [];
  final WordRepository _wordRepository = DatabaseService().wordRepository;
  final AIService _openAIService = AIService();
  
  // AI解析相关状态
  bool _isLoadingAI = false;
  String? _aiMeaning;
  String? _aiExamples;
  
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _loadWords();
    _openAIService.init();
  }
  
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _loadWords();
  }
  
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      _loadWords();
    }
  }
  
  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
  
  Future<void> _loadWords() async {
    setState(() {
      _isLoading = true;
    });
    
    try {
      final words = await _wordRepository.getAllWords();
      
      // 提取所有类别
      final Set<String> categories = {'全部'};
      for (var word in words) {
        if (word.category != null && word.category!.isNotEmpty) {
          categories.add(word.category!);
        }
      }
      
      setState(() {
        _words = words;
        _filteredWords = words;
        _categories = categories.toList();
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('加载单词失败: $e', style: const TextStyle(fontFamily: 'FangSong'))),
      );
    }
  }
  
  void _filterWordsByCategory(String category) {
    setState(() {
      _selectedCategory = category;
      if (category == '全部') {
        _filteredWords = _words;
      } else {
        _filteredWords = _words.where((word) => word.category == category).toList();
      }
      _currentIndex = 0;
      _showMeaning = false;
      // 重置AI解析结果
      _aiMeaning = null;
      _aiExamples = null;
    });
  }
  
  void _shuffleWords() {
    setState(() {
      _filteredWords.shuffle();
      _currentIndex = 0;
      _showMeaning = false;
      _isShuffled = true;
      // 重置AI解析结果
      _aiMeaning = null;
      _aiExamples = null;
    });
  }
  
  void _resetOrder() {
    setState(() {
      _filterWordsByCategory(_selectedCategory);
      _isShuffled = false;
      // 重置AI解析结果
      _aiMeaning = null;
      _aiExamples = null;
    });
  }
  
  /// 获取AI解析
  Future<void> _getAIExplanation(String word) async {
    // 检查是否设置了API密钥
    final hasApiKey = await _openAIService.hasApiKey();
    if (!hasApiKey) {
      final result = await AIService.showApiKeyDialog(context);
      if (!result) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('未设置阿里云API密钥，无法使用AI解析功能', style: TextStyle(fontFamily: 'FangSong'))),
        );
        return; // 用户取消了设置
      }
    }
    
    setState(() {
      _isLoadingAI = true;
    });
    
    try {
      final explanation = await _openAIService.getWordExplanation(word);
      
      setState(() {
        _aiMeaning = explanation['meaning'] ?? '';
        _aiExamples = explanation['examples'] ?? '';
        _isLoadingAI = false;
      });
    } catch (e) {
      setState(() {
        _isLoadingAI = false;
      });
      
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('获取AI解析失败: $e', style: const TextStyle(fontFamily: 'FangSong'))),
        );
      }
    }
  }
  
  void _toggleMeaning() {
    setState(() {
      _showMeaning = !_showMeaning;
      // 重置AI解析结果
      _aiMeaning = null;
      _aiExamples = null;
    });
  }
  
  void _nextCard() {
    if (_filteredWords.isEmpty) return;
    
    setState(() {
      _currentIndex = (_currentIndex + 1) % _filteredWords.length;
      _showMeaning = false;
      // 重置AI解析结果
      _aiMeaning = null;
      _aiExamples = null;
    });
  }
  
  void _previousCard() {
    if (_filteredWords.isEmpty) return;
    
    setState(() {
      _currentIndex = (_currentIndex - 1 + _filteredWords.length) % _filteredWords.length;
      _showMeaning = false;
      // 重置AI解析结果
      _aiMeaning = null;
      _aiExamples = null;
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('卡片记忆', style: TextStyle(fontFamily: 'FangSong')),
        centerTitle: true,
        actions: [
          IconButton(
            icon: Icon(_isShuffled ? Icons.sort : Icons.shuffle),
            tooltip: _isShuffled ? '恢复顺序' : '随机排序',
            onPressed: _isShuffled ? _resetOrder : _shuffleWords,
          ),
          PopupMenuButton<String>(
            icon: const Icon(Icons.filter_list),
            tooltip: '按类别筛选',
            onSelected: _filterWordsByCategory,
            itemBuilder: (BuildContext context) {
              return _categories.map((String category) {
                return PopupMenuItem<String>(
                  value: category,
                  child: Text(
                    category,
                    style: TextStyle(
                      fontWeight: _selectedCategory == category
                          ? FontWeight.bold
                          : FontWeight.normal,
                      color: _selectedCategory == category
                          ? Theme.of(context).primaryColor
                          : null,
                      fontFamily: 'FangSong',
                    ),
                  ),
                );
              }).toList();
            },
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _filteredWords.isEmpty
              ? const Center(child: Text('没有找到单词，请添加单词或更改筛选条件', style: TextStyle(fontFamily: 'FangSong')))
              : SafeArea(
                  child: ListView(
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    children: [
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 16),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '类别: $_selectedCategory',
                              style: Theme.of(context).textTheme.titleSmall?.copyWith(fontFamily: 'FangSong'),
                            ),
                            Text(
                              '${_currentIndex + 1}/${_filteredWords.length}',
                              style: Theme.of(context).textTheme.titleMedium?.copyWith(fontFamily: 'FangSong'),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 20),
                      GestureDetector(
                        onTap: _toggleMeaning,
                        onHorizontalDragEnd: (details) {
                          if (details.primaryVelocity! > 0) {
                            // 右滑，显示上一个
                            _previousCard();
                          } else if (details.primaryVelocity! < 0) {
                            // 左滑，显示下一个
                            _nextCard();
                          }
                        },
                        child: Card(
                          elevation: 5,
                          margin: const EdgeInsets.symmetric(horizontal: 32, vertical: 16),
                          child: Container(
                            width: double.infinity,
                            padding: const EdgeInsets.all(16),
                            child: ListView(
                                padding: EdgeInsets.zero,
                                shrinkWrap: true,
                                physics: const ClampingScrollPhysics(),
                                children: [
                                  if (_filteredWords[_currentIndex].pronunciation != null) ...[  
                                    Text(
                                      _filteredWords[_currentIndex].pronunciation!,
                                      style: Theme.of(context).textTheme.titleMedium!.copyWith(
                                        fontStyle: FontStyle.italic,
                                        color: Colors.grey[600],
                                        fontFamily: 'Arial',
                                      ),
                                      textAlign: TextAlign.center,
                                    ),
                                    const SizedBox(height: 10),
                                  ],
                                  Text(
                                    _filteredWords[_currentIndex].word,
                                    style: Theme.of(context).textTheme.headlineMedium?.copyWith(fontFamily: 'FangSong'),
                                    textAlign: TextAlign.center,
                                  ),

                                  const SizedBox(height: 20),
                                  if (_showMeaning) ...[  
                                    const Divider(),
                                    if (_filteredWords[_currentIndex].meaning != null) ...[  
                                      Text(
                                        _filteredWords[_currentIndex].meaning!,
                                        style: Theme.of(context).textTheme.titleLarge?.copyWith(fontFamily: 'FangSong'),
                                        textAlign: TextAlign.center,
                                      ),
                                    ],
                                    if (_filteredWords[_currentIndex].example != null) ...[  
                                      const SizedBox(height: 15),
                                      Text(
                                        _filteredWords[_currentIndex].example!,
                                        style: Theme.of(context).textTheme.bodyMedium!.copyWith(
                                          fontFamily: 'FangSong',
                                        ),
                                        textAlign: TextAlign.center,
                                      ),
                                    ],
                                    
                                    // AI解析按钮
                                    const SizedBox(height: 20),
                                    if (_aiMeaning == null && _aiExamples == null) ...[  
                                      ElevatedButton.icon(
                                        onPressed: _isLoadingAI ? null : () => _getAIExplanation(_filteredWords[_currentIndex].word),
                                        icon: _isLoadingAI 
                                            ? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2))
                                            : const Icon(Icons.psychology),
                                        label: Text(_isLoadingAI ? '加载中...' : '阿里云解析', style: const TextStyle(fontFamily: 'FangSong')),
                                      ),
                                    ] else ...[  
                                      const Divider(height: 30),
                                      const Text(
                                        'AI解析',
                                        style: TextStyle(fontWeight: FontWeight.bold, color: Colors.blue, fontFamily: 'FangSong'),
                                      ),
                                      const SizedBox(height: 10),
                                      if (_aiMeaning != null) ...[  
                                        Container(
                                          width: double.infinity,
                                          constraints: const BoxConstraints(maxHeight: 200),
                                          decoration: BoxDecoration(
                                            color: Colors.blue.shade50,
                                            borderRadius: BorderRadius.circular(8),
                                            border: Border.all(color: Colors.blue.shade200),
                                          ),
                                          child: Scrollbar(
                                            thumbVisibility: true,
                                            child: ListView(
                                              padding: const EdgeInsets.all(12),
                                              children: [
                                                const Text(
                                                  '含义:',
                                                  style: TextStyle(
                                                    fontWeight: FontWeight.bold,
                                                    color: Colors.blue,
                                                    fontFamily: 'FangSong',
                                                  ),
                                                ),
                                                const SizedBox(height: 6),
                                                Text(
                                                  _aiMeaning!,
                                                  style: Theme.of(context).textTheme.titleMedium?.copyWith(fontFamily: 'FangSong'),
                                                  textAlign: TextAlign.start,
                                                ),
                                                if (_aiExamples != null && _aiExamples!.isNotEmpty) ...[  
                                                  const SizedBox(height: 12),
                                                  const Text(
                                                    '例句:',
                                                    style: TextStyle(
                                                      fontWeight: FontWeight.bold,
                                                      color: Colors.blue,
                                                      fontFamily: 'FangSong',
                                                    ),
                                                  ),
                                                  const SizedBox(height: 6),
                                                  Text(
                                                    _aiExamples!,
                                                    style: Theme.of(context).textTheme.bodyMedium!.copyWith(
                                                      fontFamily: 'FangSong',
                                                    ),
                                                    textAlign: TextAlign.start,
                                                  ),
                                                ],
                                              ],
                                            ),
                                          ),
                                        ),
                                      ],
                                    ],
                                  ] else ...[  
                                    const Text(
                                      '点击查看释义和例句',
                                      style: TextStyle(color: Colors.grey, fontFamily: 'FangSong'),
                                    ),
                                  ],
                                ],
                              ),
                            ),
                          ),
                        ),
                      const SizedBox(height: 10),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          ElevatedButton.icon(
                            onPressed: _previousCard,
                            icon: const Icon(Icons.arrow_back),
                            label: const Text('上一个', style: TextStyle(fontFamily: 'FangSong')),
                          ),
                          const SizedBox(width: 20),
                          ElevatedButton.icon(
                            onPressed: _nextCard,
                            icon: const Icon(Icons.arrow_forward),
                            label: const Text('下一个', style: TextStyle(fontFamily: 'FangSong')),
                          ),
                        ],
                      ),
                      const SizedBox(height: 10),
                      Text(
                        '左右滑动可切换单词',
                        style: Theme.of(context).textTheme.bodySmall!.copyWith(color: Colors.grey, fontFamily: 'FangSong'),
                      ),
                      const SizedBox(height: 10),
                    ],
                  ),
                ),
    );
  }
}